<?php
/**
 * Created by PhpStorm.
 * User: Love
 * Date: 2018/8/30
 * Time: 17:04
 */

namespace App\Traits;


use Doctrine\Common\Cache\Cache;

trait MemoryCacheTrait
{
    public static function create($data = null){
        if ($data == null){
            return null;
        }
        $instance = new static;
        foreach ($data as $key => $value){
            $instance[$key] = $value;
        }
        return $instance;
    }
    /**
     * 如果方法是 find($id, $nocache)
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return mixed
     */
    public static function __callStatic($method, $parameters)
    {
        if ($method == 'find'){
            // 从缓存中获取数据
            $obj = static::create(json_decode(Cache::get(static::getCacheKey($parameters[0])), true));
            if (null == $obj){
                $obj = (new static)->$method(...$parameters);
                if (null == $obj){
                    return null;
                } else {
                    $key = static::getCacheKey($parameters[0]);
                    // 设置缓存及过期时间
                    Cache::set($key, $obj);
                    Cache::expire($key, static::$expire_time);
                    return $obj;
                }
            } else {
                $obj->exists = true;
                return $obj;
            }
        } else if($method == 'findNoCache'){
            $method = 'find';
            return (new static)->$method(...$parameters);
        }

        return (new static)->$method(...$parameters);
    }
}